package com.letter.otools.day.search;

import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;

import static org.litepal.LitePalApplication.getContext;

import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.letter.otools.day.BaseActivity;
import com.letter.otools.day.R;
import com.letter.otools.day.diary.Diary;
import com.letter.otools.day.diary.DiaryDetailActivity;
import com.letter.otools.day.diary.DiaryTimelineAdapter;
import com.letter.otools.day.util.AppUtils;
import com.letter.otools.day.util.StringUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.litepal.FluentQuery;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity implements View.OnClickListener {

    private ActionBar actionBar;
    //    private SearchView searchView;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private AppCompatEditText searchInput;
    int page = 1;
    int limit = 20;

    @Override
    public void onClick(View view) {

    }

    void initToolBar() {
        Toolbar toolbar = findViewById(R.id.Toolbar);
        setSupportActionBar(toolbar);

        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(AppUtils.getNightMode(this) == MODE_NIGHT_YES ? R.drawable.ic_toolbar_back_white_24dp : R.drawable.ic_toolbar_back_gray_24dp);
//            actionBar.setTitle("");
            actionBar.setDisplayShowTitleEnabled(false);
        }

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_search;
    }

    DiaryTimelineAdapter diaryAdapter;

    @Override
    protected void initData() {
        registerForActivityResult();
    }

    @Override
    protected void initView() {
        initToolBar();
//        searchView = findViewById(R.id.searchView);
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshLayout);
//        searchView.setIconified(false);
//        searchView.setIconifiedByDefault(false);
//        searchView.onActionViewExpanded();
//        searchView.setOnSearchClickListener(view -> {
//
//        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                loadData(1);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                loadData(2);
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(diaryAdapter = new DiaryTimelineAdapter(diaryList, 0));
        diaryAdapter.setPositionListener((p, d) -> {
            switch (p) {
                case 1:
                    Intent intent = new Intent(getActivity(), DiaryDetailActivity.class);
                    intent.putExtra("diaryId", ((Diary) d).getId());
                    launchForResult(intent);
                    break;
            }
        });
        refreshLayout.autoRefresh(100);
        searchInput = findViewById(R.id.searchInput);
        searchInput.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_DONE) {
                refreshLayout.autoRefresh(100);
                return true;
            }
            return false;
        });
    }

    private List<Diary> diaryList = new ArrayList<>();

    private String keyword = "哇";

    void loadData(int type) {
        keyword = searchInput.getText().toString();

        FluentQuery fluentQuery = LitePal.order("id asc ")
                .limit(limit).offset((page - 1) * limit);
        if (StringUtils.isNotEmpty(keyword)) {
            String whe = "title like ? or content like ?";
            fluentQuery.where(whe, '%' + this.keyword + '%', '%' + this.keyword + '%');
        }

        List<Diary> anniversaryList = fluentQuery.find(Diary.class);

        if (type == 1) {
            diaryList.clear();
            refreshLayout.finishRefresh(100, true, anniversaryList == null || anniversaryList.size() < limit);//传入false表示刷新失败
        }
        if (type == 2) {
            refreshLayout.finishLoadMore(100, true, anniversaryList == null || anniversaryList.size() < limit);//传入false表示刷新失败
        }

        if (anniversaryList != null && !anniversaryList.isEmpty()) {
            this.diaryList.addAll(anniversaryList);
        }
        diaryAdapter.notifyDataSetChanged();
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // 加载菜单资源
//        getMenuInflater().inflate(R.menu.menu_toolbar, menu);
//
//        // 获取搜索菜单项
//        MenuItem searchItem = menu.findItem(R.id.action_search);
//        // 获取SearchView实例
//        searchView = (SearchView) searchItem.getActionView();
////        searchView.post(() -> {
////            searchView.setIconified(false);
////            searchView.setIconifiedByDefault(false);
////            searchView.onActionViewExpanded();
////        });
//        // 配置SearchView默认展开
//        // 调整搜索框的内边距
////        LinearLayout searchPlate = searchView.findViewById(androidx.appcompat.R.id.search_plate);
////        if (searchPlate != null) {
////            searchPlate.setPadding(0, 0, 0, 0); // 移除内边距
////        }
//
//        // 强制展开并填充宽度
//        searchItem.expandActionView();
//        searchView.setMaxWidth(Integer.MAX_VALUE);
//        searchView.setIconified(false); // 设置默认不折叠为图标
//        searchView.setIconifiedByDefault(false); // 设置默认不折叠为图标
//        // 配置SearchView属性
//        searchView.setQueryHint("请输入搜索内容"); // 设置提示文字
//
//        // 设置搜索事件监听
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            // 当用户提交搜索时触发
//            @Override
//            public boolean onQueryTextSubmit(String query) {
////                Toast.makeText(MainActivity.this, "搜索: " + query, Toast.LENGTH_SHORT).show();
//                // 关闭搜索框
////                searchItem.collapseActionView();
//                return true;
//            }
//
//            // 当搜索内容变化时触发（实时搜索）
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                // 可以在这里实现实时过滤功能
//                return true;
//            }
//        });
//
//        // 搜索框关闭监听
//        searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item) {
//                // 搜索框展开时的操作
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item) {
//                // 搜索框关闭时的操作，如清除搜索结果
//                return true;
//            }
//        });
//        return true;
//    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
